package cn.zclong.article.web.servlet.admin;

import cn.itcast.servlet.BaseServlet;
import cn.zclong.article.domain.Article;
import cn.zclong.article.domain.PageBean;
import cn.zclong.article.service.ArticleService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 管理员审核文章
 */

public class AdminArticleServlet extends BaseServlet {
	private ArticleService articleService = new ArticleService();

	
	/**
	 * 管理员删除帖子
	 */

	public String delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 先获取帖子的id
		 * 调用service方法，删除该帖子
		 */
		String id = request.getParameter("id");
		articleService.delete(id);
		return findAll(request, response);
	}

	
	
	/**
	 * 更改管理员的审核状态
	 */

	public String update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 先获取帖子的id
		 * 调用service方法，把该帖子的审核状态修改
		 * 1：管理员审核通过
		 * 0：不通过
		 */
		String id = request.getParameter("id");
		articleService.update(id);
		return findAll(request, response);
	}

	/*
	 * 根据id查找帖子，显示帖子的内容
	 */
	public String adminFindById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 得到id
		String id = request.getParameter("id");

		// 得到Article对象
		Article form = articleService.adminFindById(id);

		// 得到时间
		long time = form.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time1 = sdf.format(new Date(time));
		request.setAttribute("time1", time1);

		request.setAttribute("form", form);

		return "f:/adminjsps/admin/article/article.jsp";
	}

	/**
	 * 显示所有帖子
	 */
	public String findAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 分页查询所有数据 1，获取页面传递的pc当前页码 2，给定ps的值，每页记录数
		 * 3，使用pc和ps调用的service方法，得到PageBean,保存到request域 4，转发到in.jsp
		 */
		int pc = getPc(request);// 得到pc
		int ps = 5;// 给定ps的值，每页五行记录
		PageBean<Article> pb = articleService.adminFindAll(pc, ps);// 传递pc和ps给service方法，得到PageBean
		request.setAttribute("pb", pb);// 保存到request域
		return "f:/adminjsps/admin/article/list.jsp";
	}

	/*
	 * 获取pc当前页码
	 */
	public int getPc(HttpServletRequest request) {
		String value = request.getParameter("pc");
		if (value == null || value.trim().isEmpty()) {
			return 1;// pc位null，表示只有一页
		}
		return Integer.parseInt(value);// 把pc转换成int类型
	}
}
